package com.pathfinder.utils;

import android.util.Pair;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;

import static java.net.URLEncoder.encode;

/**
 * Date: 08.05.11
 *
 * @author Victor Passichenko (vpas@yandex-team.ru)
 */
public class ClientUtils {

    private static final String DEFAULT_ENCODING = "UTF-8";

    public static String getPostParameters(List<BasicNameValuePair> data) {
        StringBuilder parameters = new StringBuilder();

        try {
            for (int i = 0; i < data.size(); i++) {
                if (i != 0) {
                    parameters.append("&");
                }

                parameters
                        .append(URLEncoder.encode(data.get(i).getName(), DEFAULT_ENCODING))
                        .append("=")
                        .append(URLEncoder.encode(data.get(i).getValue(), DEFAULT_ENCODING));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.out.println("Yura is stupid - java do not know this encoding : " + DEFAULT_ENCODING);
        }

        return parameters.toString();
    }

    public static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 10000;
    public static final int DEFAULT_READ_TIMEOUT_MILLIS = 10000;

    public static String getByUrl(String url) {
        try {
            InputStream is = fetchInputStream(new URL(url), DEFAULT_CONNECT_TIMEOUT_MILLIS, DEFAULT_READ_TIMEOUT_MILLIS);
            return getTextFromInputStream(is);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            Log.error("Error making get request to " + url, e);
            return null;
        }
    }

    public static String makePostRequest(String urlStr, Collection<Pair<String, String>> keyValuePairs) {
        if (keyValuePairs.size() == 0) {
            throw new IllegalArgumentException("keyValuePairs is empty!");
        }

        try {
            // Construct data
            StringBuilder sb = new StringBuilder();
            for (Pair<String, String> keyValue : keyValuePairs) {
                sb.append(encode(keyValue.first, DEFAULT_ENCODING)).append("=").
                        append(encode(keyValue.second, DEFAULT_ENCODING)).append("&");
            }

            String data = sb.substring(0, sb.length() - 1);

            // Send data
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            String response = getTextFromInputStream(conn.getInputStream());
            wr.close();

            return response;
        } catch (Exception e) {
            Log.error("Error while doing post request!", e);
            return null;
        }
    }

    public static InputStream fetchInputStream(URL url, int connectTimeout, int readTimeout) throws IOException {
        URLConnection uc = url.openConnection();
        uc.setConnectTimeout(connectTimeout);
        uc.setReadTimeout(readTimeout);
        uc.connect();
        // returned input stream should be already buffered inside
        return uc.getInputStream();
    }

    public static String getTextFromInputStream(InputStream input)
            throws IOException {
        StringBuffer content = new StringBuffer();

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(input), 8 * 1024);

        String line = null;
        boolean first = true;

        while ((line = reader.readLine()) != null) {
            if (!first) {
                content.append(System.getProperty("line.separator"));
            } else {
                first = false;
            }

            content.append(line);
        }

        reader.close();

        return content.toString();
    }
}
